﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JCSoft.Collect.Data;
using NHibernate;

namespace JCSoft.Collect.Bussness
{
    public interface IUserManager
    {
        void Create(User user);
        void Update(User user);
        void Delete(int userId);
        User GetUser(int userId);
        User GetUser(string userName, string password);

        EventHandler Created { get; set; }
        EventHandler Updated { get; set; }
        EventHandler Deleted { get; set; }
    }

    public class UserManager : DataManagerBase, IUserManager
    {
        public UserManager(MiddleTier middleTier)
            : base(middleTier)
        { }

        public UserManager(MiddleTier middleTier, IRepositoryFactory repositoryFactory)
            : base(middleTier, repositoryFactory)
        { }

        #region IUserManager 成员

        public void Create(User user)
        {
            using (var repostory = new UserRepository())
            {
                repostory.AddOnSubmit(user);
                repostory.SubmitChanges();
            }

            if (Created != null)
            {
                Created(user, new EventArgs());
            }
        }

        public void Update(User user)
        {
            using (var repository = new UserRepository())
            {
                var userToEdit = repository.GetUser(u => u.UserID == user.UserID);
                userToEdit.Email = user.Email;
                repository.SubmitChanges();
            }
        }

        public void Delete(int userId)
        {
            using (var repository = new UserRepository())
            {
                var user = repository.GetUser(u => u.UserID == userId);
                repository.DeleteOnSubmit(user);
                repository.SubmitChanges();
            }
        }

        public EventHandler Created { get; set; }

        public EventHandler Updated { get; set; }

        public EventHandler Deleted { get; set; }


        public User GetUser(int userId)
        {
            using (var repository = new UserRepository())
            {
                return repository.GetUser(u => u.UserID == userId);
            }
        }

        public User GetUser(string userName, string password)
        {
            using (var repository = new UserRepository())
            {
                return repository.GetUser(u => u.UserName.Equals(userName) && u.Password.Equals(password));
            }
        }

        #endregion
    }
}
